package com.yuntoyun.codeavatar.app.activity.main;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.google.gson.JsonObject;
import com.yuntoyun.codeavatar.app.R;
import com.yuntoyun.codeavatar.app.activity.basic.LoginActivity;
import com.yuntoyun.codeavatar.app.fwcore.activity.WebPageActivity;
import com.yuntoyun.codeavatar.app.fwcore.core.AppCoreSign;
import com.yuntoyun.fwcore.appext.data.AppData;
import com.yuntoyun.fwcore.base.FwBaseSwipeRefreshViewPagerFragment;
import com.yuntoyun.fwcore.model.FwResultJsonDataModel;
import com.yuntoyun.fwcore.model.FwResultJsonListDataModel;
import com.yuntoyun.fwcore.plug.image.glide.PlugGlide;
import com.yuntoyun.fwcore.plug.network.retrofit.FwOkHttp;
import com.yuntoyun.fwcore.tool.login.LoginTool;
import com.yuntoyun.fwcore.util.FwAlertDialogUtil;
import com.yuntoyun.fwcore.util.FwIntentUtil;
import com.yuntoyun.fwcore.util.FwLogUtil;
import com.yuntoyun.fwcore.util.FwToastUtil;
import com.yuntoyun.fwcore.view.FwCircleImageView;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

import static android.app.Activity.RESULT_OK;

/**
 * 阴影网址：https://github.com/lihangleo2/ShadowLayout
 */
public class OwnerFragment extends FwBaseSwipeRefreshViewPagerFragment {

    private final String fTag = OwnerFragment.class.getSimpleName();

    private final int gActionLoad = 901;
    private final int gActionPopular = 902;
    private final int gActionPartner = 903;
    private final int gActionGrant = 904;
    private final int gActionPartnerImage = 905;

    private final int gRcodeLogin = 801;

    @BindView(R.id.fwCiv_portrait)
    FwCircleImageView fwCiv_portrait;
    @BindView(R.id.tvw_user_name)
    TextView tvw_user_name;
    @BindView(R.id.llt_level_container)
    LinearLayout llt_level_container;
    @BindView(R.id.tvw_user_balance)
    TextView tvw_user_balance;
    @BindView(R.id.tvw_income_subtotal)
    TextView tvw_income_subtotal;
    @BindView(R.id.tvw_withdrawcash_subtotal)
    TextView tvw_withdrawcash_subtotal;
    @BindView(R.id.ivw_partner_enter)
    ImageView ivw_partner_enter;
    @BindView(R.id.llt_fans_container)
    LinearLayout llt_fans_container;
    @BindView(R.id.llt_partner_container)
    LinearLayout llt_partner_container;

    @BindView(R.id.tvw_service_code)
    TextView tvw_service_code;
    @BindView(R.id.llt_merchant_container)
    LinearLayout llt_merchant_container;

    private String partnerBannerUrl;

    @Override
    protected boolean isAgainCreateView() {
        return false;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_main_owner;
    }

    @Override
    protected void initSwipeView(View layoutView) {

    }

    @Override
    protected void reloadData() {
        if (LoginTool.isLogin()) {
            HashMap<String, Object> map = new HashMap<>();
            AppCoreSign.addSign(map);
            Observable<FwResultJsonDataModel> observable =
                    FwOkHttp.getFwAPIService().getMemberInfo(map);
            super.doPostData(this.gActionLoad, observable, true);
        } else {
            if (null != srl_swipeRefreshLayout) {
                //禁用下拉刷新
                srl_swipeRefreshLayout.setEnabled(false);
            }
            //未登录
            initData();
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {
        fwCiv_portrait.setOnClickListener(this);
        tvw_user_name.setOnClickListener(this);
    }

    @Override
    protected void initNavigation() {

    }

    @Override
    protected void messageHandler(Message msg) {

    }

    @Override
    protected void messageHandler(FwResultJsonDataModel model) {
        switch (model.getIndex()) {
            case gActionLoad:
                this.setLoadData(model.getFwData());
                break;
            case gActionPopular:
                this.doActionPopular(fwGsonUtil.getString(model.getFwData(), "url"));
                break;
            case gActionPartner:
                this.doLoadPartnerInfo(fwGsonUtil.getString(model.getFwData(), "url"));
                break;
            case gActionGrant:
                break;
            case gActionPartnerImage:
                break;
        }
    }

    @Override
    protected void messageHandler(FwResultJsonListDataModel model) {

    }

    @OnClick({R.id.ivw_qrcode, R.id.ivw_setting, R.id.llt_action_record,
            R.id.llt_action_order, R.id.llt_action_withdrawal, R.id.llt_action_address,
            R.id.llt_action_fans, R.id.llt_action_partner, R.id.llt_action_popular,
            R.id.llt_action_service, R.id.ivw_partner_enter, R.id.llt_action_merchant,
            R.id.llt_action_publicity})
    @Override
    public void onClick(View v) {
        if (null == v) return;

        int pViewId = v.getId();
        int pNoLogin[] = new int[]{
                R.id.ivw_setting, R.id.llt_action_popular, R.id.llt_action_service, R.id.ivw_partner_enter
        };
        boolean chkLogin = true;
        for (int id : pNoLogin) {
            if (id == pViewId) {
                chkLogin = false;
                break;
            }
        }
        if (chkLogin) {
            if (!LoginTool.isLogin(getActivity(), LoginActivity.class, gRcodeLogin)) {
                //未登录，终止运行
                return;
            }
        }

        switch (v.getId()) {
            case R.id.ivw_qrcode:
//                FwIntentUtil.builder().startActivity(fwActivity, OwnerQrcodeActivity.class);
                break;
            case R.id.ivw_setting:
//                FwIntentUtil.builder().startActivity(fwActivity, SettingActivity.class);
                break;
            case R.id.llt_action_record:
//                FwIntentUtil.builder().startActivity(fwActivity, AccountRecordActivity.class);
                break;
            case R.id.llt_action_order:
//                FwIntentUtil.builder().startActivity(fwActivity, OrderActivity.class);
                break;
            case R.id.llt_action_withdrawal:
                this.doChkWithdrawal();
                break;
            case R.id.llt_action_address:
//                FwIntentUtil.builder().startActivity(fwActivity, AddressListActivity.class);
                break;
            case R.id.llt_action_fans:
//                FwIntentUtil.builder().startActivity(fwActivity, FansListActivity.class);
                break;
            case R.id.llt_action_partner:
//                FwIntentUtil.builder().startActivity(fwActivity, PartnerListActivity.class);
                break;
            case R.id.llt_action_popular:
                this.doActionPopular(null);
                break;
            case R.id.llt_action_service:
//                FwIntentUtil.builder().startActivity(fwActivity, ServiceCenterActivity.class);
                break;
            case R.id.ivw_partner_enter:
//                FwIntentUtil.builder().startActivity(fwActivity, PartnerGoodsActivity.class);
                break;
            case R.id.llt_action_merchant:
//                FwIntentUtil.builder().startActivity(fwActivity, MerchantListActivity.class);
                break;
            case R.id.llt_action_publicity:
//                FwIntentUtil.builder().startActivity(fwActivity, PropagandaListActivity.class);
                break;
            default:
                FwLogUtil.warn(fTag, fwActivity.getString(R.string.fw_txt_no_resid));
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case gRcodeLogin:
                if (resultCode == RESULT_OK) {
                    this.reloadData();
                }
                break;
        }
    }

    @Override
    public void onResume() {
        if (TextUtils.isEmpty(partnerBannerUrl)) {
            HashMap<String, Object> map = new HashMap<>();
            AppCoreSign.addSign(map);
            Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getPartnerBanner(map);
            super.doPostData(gActionPartnerImage, observable, false);
        } else {
//            PlugGlide.init().loadImg(fwActivity, partnerBannerUrl, R.mipmap.icon_action_owner_partner_enter, ivw_partner_enter);
        }
        super.onResume();
    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    private void doChkWithdrawal() {
        HashMap<String, Object> map = new HashMap<>();
        AppCoreSign.addSign(map);
        Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getChkGrant(map);
        super.doPostData(this.gActionGrant, observable, true);
    }

    private void doLoadPartnerInfo(String url) {
        if (TextUtils.isEmpty(url)) {
            HashMap<String, Object> map = new HashMap<>();
            AppCoreSign.addSign(map);
            Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getPartnerInfo(map);
            super.doPostData(this.gActionPartner, observable, true);
        } else {
            Bundle extra = new Bundle();
            extra.putString("ext_title", "合伙人中心");
            extra.putString("ext_url", url);
            extra.putInt("ext_actionId", WebPageActivity.PARTNER_INFO);
            FwIntentUtil.builder().startActivity(fwActivity, WebPageActivity.class, extra);
        }
    }

    private void doActionPopular(String url) {
        if (TextUtils.isEmpty(url)) {
            HashMap<String, Object> map = new HashMap<>();
            AppCoreSign.addSign(map);
            Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getPopularRule(map);
            super.doPostData(this.gActionPopular, observable, true);
        } else {
            Bundle extra = new Bundle();
            extra.putString("ext_title", "推广规则");
            extra.putString("ext_url", url);
            FwIntentUtil.builder().startActivity(fwActivity, WebPageActivity.class, extra);
        }
    }

    private void setLoadData(JsonObject joData) {
        if (null != srl_swipeRefreshLayout) {
            //启用下拉刷新
            srl_swipeRefreshLayout.setEnabled(true);
        }

        //淘宝授权标识
        boolean tmpTaoBaoAuth = fwGsonUtil.getBoolean(joData, "has_taobaoAuth");
        AppData.setTaobaoAuth(tmpTaoBaoAuth);
        //提现密码标识
        boolean tmpWithdrawalPwd = fwGsonUtil.getBoolean(joData, "has_withdrawalPwd");
        AppData.setWithdrawalPwd(tmpWithdrawalPwd);
        //绑定账号标识
        boolean tmpBindAccount = fwGsonUtil.getBoolean(joData, "has_alipayAccount");
        AppData.setAlipayAccount(tmpBindAccount);

        //用户信息
        PlugGlide.init().loadImg(fwActivity, fwGsonUtil.getString(joData,
                "avatar"), R.mipmap.icon_empty_portait, fwCiv_portrait);
        tvw_user_name.setText(fwGsonUtil.getString(joData, "nickname"));
        //身份
        llt_level_container.removeAllViews();
//        //点击事件
//        llt_level_container.setOnClickListener(this);
        boolean tmpLevelVisiable1 = false;
        boolean tmpLevelVisiable2 = true;
        boolean is_shareholder = fwGsonUtil.getBoolean(joData, "is_shareholder"); //	股东身份：0 不是；1 是
        if (is_shareholder) {
            View tmpView = fwLayoutInflater.inflate(R.layout.fragment_main_owner_level_button, null);
            TextView tvw_level_name = tmpView.findViewById(R.id.tvw_level_name);
            tvw_level_name.setText(String.format("%s股东", fwGsonUtil.getString(joData, "city")));
            ImageView ivw_level_more = tmpView.findViewById(R.id.ivw_level_more);
            ivw_level_more.setVisibility(View.GONE);
            llt_level_container.addView(tmpView);
            tmpLevelVisiable1 = true;
        }
        View tmpPartnerView = fwLayoutInflater.inflate(R.layout.fragment_main_owner_level_button, null);
        ImageView ivw_level_tag2 = tmpPartnerView.findViewById(R.id.ivw_level_tag);
        TextView tvw_level_name2 = tmpPartnerView.findViewById(R.id.tvw_level_name);
        ImageView ivw_level_more2 = tmpPartnerView.findViewById(R.id.ivw_level_more);
        //当前身份(0=普通会员)
        int pAuth = AppData.getUserAuth();
        if (pAuth == 0) {
            llt_fans_container.setVisibility(View.GONE);
            llt_partner_container.setVisibility(View.GONE);
        } else {
            llt_fans_container.setVisibility(View.VISIBLE);
            llt_partner_container.setVisibility(View.VISIBLE);
            if (pAuth == 1) {
                llt_merchant_container.setVisibility(View.VISIBLE);
            } else {
                llt_merchant_container.setVisibility(View.GONE);
            }
        }
        //点击事件
        tmpPartnerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doCheckPartner();
            }
        });
        llt_level_container.setVisibility((tmpLevelVisiable1 || tmpLevelVisiable2) ? View.VISIBLE : View.GONE);
        //金额
        tvw_user_balance.setText(fwGsonUtil.getString(joData, "balance"));
        tvw_income_subtotal.setText(fwGsonUtil.getString(joData, "income_amount"));
        tvw_withdrawcash_subtotal.setText(fwGsonUtil.getString(joData, "withdrawal_amount"));

        if (joData.has("service_code")) {
            tvw_service_code.setText(String.format("客服码：%s", fwGsonUtil.getString(joData, "service_code")));
            tvw_service_code.setVisibility(View.VISIBLE);
        } else {
            tvw_service_code.setVisibility(View.GONE);
        }
    }

    private void doCheckPartner() {
        int pAuth = AppData.getUserAuth();
        if (3 == pAuth) {
            FwAlertDialogUtil.builder().showCustomConfirmDialog(fwActivity, "提示", "合伙人已到期，请续费", "取消",
                    "去续费", new FwAlertDialogUtil.CustomClickListener() {
                        @Override
                        public void clickPositiveButton(DialogInterface dialog) {
                            //确认事件
//                            FwIntentUtil.builder().startActivity(getActivity(), PartnerGoodsActivity.class);
                        }

                        @Override
                        public void clickNegativeButton(DialogInterface dialog) {
                            //取消事件
                        }
                    });
        } else {
            this.doLoadPartnerInfo(null);
        }
    }

}
